//
//  ZMusicVC.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/9/10.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZMusicVC.h"
#import "ZZBottomSelectView.h"
#import "ZZProgressView.h"
#import "ZSelectView.h"
#import "CHcir_Slider.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "ZZMusicListController.h"
#import "musicTool.h"
#import "ZZMusicList.h"
#import "ZZMusicModel.h"
#import "ZZCenterView.h"
#import "ZZCircleTool.h"
#import "UIImage+ZUtilities.h"
#import "ZZView.h"
#import "UIColor+ZUtilities.h"
#import "ZZDeviceManager.h"
#import "ZDrawboadView.h"
#import "ZZMusicDuoSeSelctController.h"
#import "ZZLightViewCellModel.h"
#import "ZZMusicLightTool.h"
#import "ZZMusicMoreDuoseSelctController.h"
#import "ZZMusicMoreLightTool.h"

static CGAffineTransform tansform;
static CGFloat a = -1;


#define kOneColor @"oneColor"
#define kTwoColor @"twoColor"
#define  kPlayMusic @"playMusic"

@interface ZMusicVC ()<CHcirsliderDelegate,AVAudioPlayerDelegate>

@property (nonatomic, strong)ZZBottomSelectView *bottomView;

@property (nonatomic, strong)UILabel *musicLabel;

// 音乐数据库
@property (nonatomic, strong)NSMutableArray<ZZMusicModel *> *musicList;

@property (nonatomic, assign)ZSelectPlayModel playModel;
// 音乐实际播放的列表
@property (nonatomic, strong)NSMutableArray<ZZMusicModel *> *playMusicList;
// 当前播放的音乐
@property (nonatomic, strong)ZZMusicModel *currentMusic;

@property (nonatomic, strong)ZSelectView *selectView;

// 当前播放的歌曲
@property (nonatomic, assign)NSInteger currentIndex;

@property (nonatomic, assign)NSInteger currentDuration;

// 进度View
@property (nonatomic, strong)ZZProgressView *progressView;

@property (nonatomic, strong)ZZCenterView *circleView;
// 单色颜色数组
@property (nonatomic, strong)NSMutableArray *danSeArr;
// 多色颜色数组
@property (nonatomic, strong)NSMutableArray *duoSeArr;
// 多色model
@property (nonatomic, strong)ZZLightViewCellModel *duoseModel;
// 渐变多色
@property (nonatomic, strong)ZZLightViewCellModel *moreDuoSeModel;
// 渐变多色Arr
@property (nonatomic, strong)NSMutableArray *moreDuoSeArr;
// 外圈View
@property (nonatomic, strong)UIView *circleSelectView;
// 内圈View
@property (nonatomic, strong)UIView *inCircleView;

@property (nonatomic, strong)UIButton *selectBtn;

@property (nonatomic, strong)UIButton *addMusicBtn;

// 跳蚤模式切换按钮
@property (nonatomic, assign)NSInteger selectTopBtnModel;

// 跳屏渐变发送蓝牙数据的colors
@property (nonatomic, strong)NSArray *mtbTiaoPinColor;

@property (nonatomic, weak)ZZDeviceManager *devicemanager;

// 单色选择颜色View
@property (nonatomic, strong)UIView *danSeSelectView;

@property (nonatomic, strong)ZDrawboadView *boadView;

@property (nonatomic, strong)UIButton *addColorBtn;

@property (nonatomic, assign)CGFloat lingMingDu;

@property (nonatomic, assign)CGFloat minValue;

@property (nonatomic, assign)CGFloat maxValue;

@property (nonatomic, assign)CGAffineTransform originTransForm;

@end

@implementation ZMusicVC {
    
    AVAudioPlayer *_avAudioPlayer; // 播放器palyer
    UISlider *_pregressSlider; // 播放进度
    UILabel *_pregressLabel; // 进度
    UISlider *_volumeSlider;   // 声音控制
    NSTimer *_timer; // 监控音频播放进度
    
    AVAudioRecorder*recorder;
    NSTimer *levelTimer;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    static id ID = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        ID = [super allocWithZone:zone];
    });
    
    return ID;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.titleView = [UIImageView zImageViewWithImage:@"img_logo"];
    self.navigationItem.rightBarButtonItem =  self.navigationItem.rightBarButtonItem = [self zNavItemWithImage:@"icon_lanmu" shouldOriginal:YES andSelector:@selector(rightNavItemClick)];
    
    UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectBtn = selectBtn;
    selectBtn.frame = CGRectMake(0, 0, 60, 28);
    [selectBtn setImage:[UIImage imageNamed:@"btn_yy"] forState:UIControlStateNormal];
    [selectBtn setImage:[UIImage imageNamed:@"btn_wy"] forState:UIControlStateSelected];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:selectBtn];
    [selectBtn addTarget:self action:@selector(selectBtnDidClick) forControlEvents:UIControlEventTouchDown];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.bottomView.frame = CGRectMake(40 * Z_Scale , 20 * Z_Scale + 64, Z_SCREEN_WIDTH - 40 * Z_Scale * 2, 33);
        
        self.bottomView.layer.masksToBounds = YES;
        self.progressView.frame = CGRectMake(0, CGRectGetMaxY(_musicLabel.frame) + 18 * Z_Scale, Z_SCREEN_WIDTH, 22);
        
        self.selectView.frame = CGRectMake(0, 20*Z_Scale + CGRectGetMaxY(_progressView.frame), Z_SCREEN_WIDTH, 18);
        
    });
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inBack) name:@"inBackNotification" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(inActive) name:@"inActiveNotification" object:nil];
    
    self.originTransForm = self.circleSelectView.transform;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.bottomView.frame = CGRectMake(40 * Z_Scale , 20 * Z_Scale + 64, Z_SCREEN_WIDTH - 40 * Z_Scale * 2, 33);
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    self.bottomView.frame = CGRectMake(40 * Z_Scale , 20 * Z_Scale + 64, Z_SCREEN_WIDTH - 40 * Z_Scale * 2, 33);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if(self.bottomView == nil) {

        [self cancleLuYin];
        

         [self setupSubView];

        [self playerForIndex:self.currentIndex];
        self.selectView.pauseMusic(NO);
        self.selectView.isPlayer = NO;
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (recorder != nil) {
        
        [recorder stop];
    }
    //    [self.tabBarController.tabBar setHidden:YES];
    //    [self.tabBarController.tabBarController setHidesBottomBarWhenPushed:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    //
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Func

- (void)inActive {
    
    if (self.selectBtn) {
        
        
        [self luyin];
        
      
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)inBack {
    
    
        
    [self cancleLuYin];
    
}
- (void)rightNavItemClick {
    
    if (self.devicemanager) {
        
        [self.devicemanager removeFromSuperview];
        self.devicemanager = nil;
        return;
    }
    
    ZZDeviceManager *manager = [ZZDeviceManager xibInstance];
    manager.vc = self;
    
    self.devicemanager = manager;
    manager.frame = CGRectMake(Z_SCREEN_WIDTH, 64, Z_SCREEN_WIDTH, Z_SCREEN_HEIGHT - 64);
    [self.tabBarController.view addSubview:manager];
    
    [UIView animateWithDuration:0.4 animations:^{
        
        manager.x = 0;
    }];
}

// 录音
- (void)luyin {
        
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
        /* 不需要保存录音文件 */
        NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
        //    [session setActive:YES error:nil];
        NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
                                  [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                                  [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
                                  nil];
        
        NSError *error;
        [self cancleLuYin];
          levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.2 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
        recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
        if (recorder)
        {
            
            if ([recorder prepareToRecord]) {
                recorder.meteringEnabled = YES;
                [recorder record];
                [_timer invalidate];
                _timer = nil;
            }
            
        }
        else
        {
            ZLog(@"%@", [error description]);
            
        }
}

// 取消录音
- (void)cancleLuYin{
    
    if(recorder != nil) {
        
        [recorder stop];
        recorder = nil;
        [levelTimer invalidate];
        levelTimer = nil;
    }
}

/**
 根据环境获取录音的大小
 */
- (void)levelTimerCallback:(NSTimer *)timer {
    [recorder updateMeters];
    
    float  level;                // The linear 0.0 .. 1.0 value we need.
    float  minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
    float  decibels    = [recorder averagePowerForChannel:0];
    
    if (decibels < minDecibels)
    {
        level = 0.0f;
    }
    else if (decibels >= 0.0f)
    {
        level = 1.0f;
    }
    else
    {
        float  root            = 2.0f;
        float  minAmp          = powf(10.0f, 0.05f * minDecibels);
        float  inverseAmpRange = 1.0f / (1.0f - minAmp);
        float  amp             = powf(10.0f, 0.05f * decibels);
        float  adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    /* level 范围[0 ~ 1], 转为[0 ~120] 之间 */
    dispatch_async(dispatch_get_main_queue(), ^{
        //        [_textLabel setText:[NSString stringWithFormat:@"%f", level*120]];
        ZLog(@"---分贝值：：：：%@",[NSString stringWithFormat:@"%f", level*120]);

        if (a == -1) {
            a = 0;
            tansform= self.circleSelectView.transform;
        }
        
        
        CGFloat currentFloat = level * 120;
        //        CGPoint center = self.circleView.center;
        // 10 ~ 100 // 灵敏最高是 40
        CGFloat value = 100 * (1 - (self.maxValue - self.minValue));
        CGFloat scale = currentFloat / value;
        if (scale < 0.2) {
            
            return;
        }
        if (scale >= 1) {
            
            scale = 1;
        }
        if (self.selectTopBtnModel == 1) { // 多色发送颜色
            
            UIImageView *imgView = [self.circleSelectView.subviews firstObject];
            
            NSInteger count = self.duoSeArr.count;
            CGFloat fenshu = 1.0/ count / 2.0;
            
            NSInteger obj = 0;
            for (NSInteger index = 0; index < count; index++) {
                if (scale < 0.5) {
                    
                    obj = 0;
                    break;
                }
                if (scale >= 1) {
                    
                    obj = count - 1;
                    break;
                }
                
                if ((0.5 + index * fenshu)  < scale && (0.5 + (index +1) *  fenshu) > scale) {
                    
                    obj = index;
                    break;
                }
            }
            
            [imgView imageWithColor:self.duoSeArr[obj]];
            
            // 发送蓝牙当前颜色
            ZLog(@"%@",self.duoSeArr[obj]);
        } else if (self.selectTopBtnModel == 0) { // 单色发送颜色
            
            NSMutableArray *outputMtbArr = [NSMutableArray array];
            for (UIColor *color in self.danSeArr) {
                
                CGFloat alpha = scale;
                if (alpha < 0.2) {
                    
                    alpha = 0.2;
                    
                } else if (alpha > 1) {
                    
                    alpha = 1;
                }
                NSArray *colorsRGB = [UIColor colorForGGB:color];
                UIColor *outPutColor = [UIColor colorWithRed:[colorsRGB[0] floatValue] / 255.0 green:[colorsRGB[1] floatValue] / 255.0 blue:[colorsRGB[2] floatValue] / 255.0 alpha:alpha];
                [outputMtbArr addObject:outPutColor];
            }
            // 发送蓝牙当前颜色
            ZLog(@"%@",outputMtbArr);
        } else {
            
            if (self.mtbTiaoPinColor.count> 0) {
                
                NSMutableArray *outputMtbArr = [NSMutableArray array];
                for (UIColor *color in self.mtbTiaoPinColor) {
                    
                    CGFloat alpha = scale;
                    if (alpha < 0.2) {
                        
                        alpha = 0.2;
                    } else if (alpha > 1) {
                        
                        alpha = 1;
                    }
                    NSArray *colorsRGB = [UIColor colorForGGB:color];
                    UIColor *outPutColor = [UIColor colorWithRed:[colorsRGB[0] floatValue] / 255.0 green:[colorsRGB[1] floatValue] / 255.0 blue:[colorsRGB[2] floatValue] / 255.0 alpha:alpha];
                    [outputMtbArr addObject:outPutColor];
                }
                // 发送蓝牙当前颜色
                ZLog(@"%@",outputMtbArr);
            }
            
        }
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.circleSelectView.transform =  CGAffineTransformScale(tansform,scale , scale);
            
        } completion:^(BOOL finished) {}];
    });
}

-(BOOL)isQuite:(NSData *)pcmData
{
    if (pcmData == nil)
    {
        return NO;
    }
    
    long long pcmAllLenght = 0;
    
    short butterByte[pcmData.length/2];
    memcpy(butterByte, pcmData.bytes, pcmData.length);//frame_size * sizeof(short)
    
    // 将 buffer 内容取出，进行平方和运算
    for (int i = 0; i < pcmData.length/2; i++)
    {
        pcmAllLenght += butterByte[i] * butterByte[i];
    }
    // 平方和除以数据总长度，得到音量大小。
    double mean = pcmAllLenght / (double)pcmData.length;
    double volume =10*log10(mean);//volume为分贝数大小
    
    
    
    if (volume >= 45) //45分贝
    {
        //在说话
        
    }
    
    return YES;
}

- (void)saveDanSeColor {
    
  NSUserDefaults *defaults =  [NSUserDefaults standardUserDefaults];
    
   UIColor *colorOne = self.danSeArr[0];
    
    ZZColorRGBA *rgbaOne = [ZZColorRGBA rgbaFromColor:colorOne];
    NSArray *oneArr = @[@(rgbaOne.R),@(rgbaOne.G),@(rgbaOne.B)];
    [defaults setObject:oneArr forKey:kOneColor];
    
    UIColor *colorTwo = self.danSeArr[1];
    ZZColorRGBA *rgbaTwo = [ZZColorRGBA rgbaFromColor:colorTwo];
    NSArray *twoArr = @[@(rgbaTwo.R),@(rgbaTwo.G),@(rgbaTwo.B)];
    [defaults setObject:twoArr forKey:kTwoColor];
}

#pragma mark - action

// 中间按钮点击
- (void)addColorBtnDidClick {
    
    if (self.selectTopBtnModel == 0) { // 单色
        
        UIWindow *window =   [UIApplication sharedApplication].keyWindow;
        [window addSubview:self.danSeSelectView];
    } else if(self.selectTopBtnModel == 1) { // 多色
        
        ZZMusicDuoSeSelctController *vc = [[ZZMusicDuoSeSelctController alloc] init];
        vc.preModel = self.duoseModel;
        vc.outPutModel = ^(ZZLightViewCellModel *model) {
          
            self.duoseModel = model;
            self.duoSeArr = [NSMutableArray arrayWithArray:[ZZColorRGBA colorsFromRGBA:model.colors]];
            
            self.bottomView.selectBtnClick(1);
#pragma 输出多色状态下颜色的值
            NSArray *outputColors = [ZZColorRGBA colorsFromRGBA:model.colors];
            
        };
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        
        ZZMusicMoreDuoseSelctController *vc = [[ZZMusicMoreDuoseSelctController alloc] init];
        vc.preModel = self.moreDuoSeModel;
        vc.outPutModel = ^(ZZLightViewCellModel *model) {
            
            self.moreDuoSeModel = model;
            self.moreDuoSeArr = [NSMutableArray arrayWithArray:[ZZColorRGBA colorsFromRGBA:model.colors]];
            
            self.bottomView.selectBtnClick(2);
        };
        [self.navigationController pushViewController:vc animated:YES];
    }

}

- (void)selectBtnDidClick {
    
    self.selectView.hidden = NO;
    self.selectBtn.selected = !self.selectBtn.selected;
    
        
    [self cancleLuYin];
    
    if ([_avAudioPlayer play]) {
        
        [_avAudioPlayer pause];
    }
    
    if (!self.selectBtn.selected) { // 音乐
        
        self.progressView.hidden = NO;
        if (self.playMusicList.count > 0) {
            
            self.musicLabel.hidden = NO;
        } else {
            
            self.addMusicBtn.hidden = NO;
        }
        
        if(_avAudioPlayer != nil) {
            
            [_avAudioPlayer play];
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(playProgress) userInfo:nil repeats:YES];
            
        
            [self cancleLuYin];
            
        }
        
    } else { // 录音
        
        if(_avAudioPlayer != nil && [_avAudioPlayer isPlaying]) {
            
            [_avAudioPlayer pause];
            
        }
      
            
            
        [self performSelector:@selector(luyin) withObject:self afterDelay:0.2];
        
            [_timer invalidate];
            _timer = nil;
        
        
        self.selectView.hidden = YES;
        self.progressView.hidden = YES;
        self.musicLabel.hidden = YES;
        
        
        self.musicLabel.hidden = YES;
        self.addMusicBtn.hidden = YES;
        
    }
}

- (void)addMusicBtnDidClick {
    
    
    ZZMusicListController * vc = [[UIStoryboard storyboardWithName:@"ZZMusicListController" bundle:nil] instantiateInitialViewController];
    
    vc.pasuseMusic = ^(ZZMusicModel *model, ZZMusicList *musicList) {
        
        if ([_avAudioPlayer isPlaying]) {
            
            [_avAudioPlayer pause];
            [self cancleLuYin];
        }
    };
    if (self.playMusicList.count > self.currentIndex) {
        
        vc.playerModel = self.playMusicList[self.currentIndex];
    }
    
    vc.playerMusic = ^(ZZMusicModel *model,ZZMusicList *musicList){
        
        self.addMusicBtn.hidden = YES;
        self.musicList = musicList.musicList;
        self.playMusicList = [NSMutableArray arrayWithArray:self.musicList];
        self.currentIndex = [musicList.musicList indexOfObject:model];
        musicList.isSelect = YES;

        [self playerForIndex:self.currentIndex];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Private Func

- (void)prepareMusic {
    
    self.playMusicList = [NSMutableArray arrayWithArray:self.musicList];
    [self playerForIndex:0];
    [_avAudioPlayer pause];
    
    
}

// 播放进度条
- (void)playProgress {
    
    [_avAudioPlayer updateMeters];
    
    
    
    CGFloat power = ([_avAudioPlayer averagePowerForChannel:0] + [_avAudioPlayer averagePowerForChannel:1])/2;
    
   
    if (a == -1) {
        a = 0;
        tansform= self.circleSelectView.transform;
    }
    // 更改当前播放时间
    NSString *currentMStr = [self FormatTime:_avAudioPlayer.currentTime / 60];
    NSString *currentSStr = [self FormatTime:(int)_avAudioPlayer.currentTime % 60];
    self.progressView.leftLabel.text = [NSString stringWithFormat:@"%@:%@",currentMStr,currentSStr];
    
    
    // 播放进度条
    self.progressView.slider.value = _avAudioPlayer.currentTime / _avAudioPlayer.duration;
    
     ZLog(@"power = %lf",power);
    
    CGFloat currentFloat = 160 + power ;
    //        CGPoint center = self.circleView.center;
    // 10 ~ 100 // 灵敏最高是 40
    CGFloat value = 160 * (self.maxValue - self.minValue);
    CGFloat scale = (value + power * 2) / value;
    if (scale < 0.2) {
        
        return;
    }
    
    if (scale >= 1) {
        
        scale = 1;
    }
    if (self.selectTopBtnModel == 1) { // 多色发送颜色
        
        UIImageView *imgView = [self.circleSelectView.subviews firstObject];
        
        NSInteger count = self.duoSeArr.count;
        CGFloat fenshu = 1.0/ count / 2.0;
        
        NSInteger obj = 0;
        for (NSInteger index = 0; index < count; index++) {
            if (scale < 0.5) {
                
                obj = 0;
                break;
            }
            if (scale >= 1) {
                
                obj = count - 1;
                break;
            }
            
            if ((0.5 + index * fenshu)  < scale && (0.5 + (index +1) *  fenshu) > scale) {
                
                obj = index;
                break;
            }
        }
        
        [imgView imageWithColor:self.duoSeArr[obj]];
        
        // 发送蓝牙当前颜色
        ZLog(@"%@",self.duoSeArr[obj]);
    } else if (self.selectTopBtnModel == 0) { // 单色发送颜色
        
        NSMutableArray *outputMtbArr = [NSMutableArray array];
        for (UIColor *color in self.danSeArr) {
            
            CGFloat alpha = scale;
            if (alpha < 0.2) {
                
                alpha = 0.2;
                
            } else if (alpha > 1) {
                
                alpha = 1;
            }
            NSArray *colorsRGB = [UIColor colorForGGB:color];
            UIColor *outPutColor = [UIColor colorWithRed:[colorsRGB[0] floatValue] / 255.0 green:[colorsRGB[1] floatValue] / 255.0 blue:[colorsRGB[2] floatValue] / 255.0 alpha:alpha];
            [outputMtbArr addObject:outPutColor];
        }
        // 发送蓝牙当前颜色
        ZLog(@"%@",outputMtbArr);
    } else {
        
        if (self.mtbTiaoPinColor.count> 0) {
            
            NSMutableArray *outputMtbArr = [NSMutableArray array];
            for (UIColor *color in self.mtbTiaoPinColor) {
                
                CGFloat alpha = scale;
                if (alpha < 0.2) {
                    
                    alpha = 0.2;
                } else if (alpha > 1) {
                    
                    alpha = 1;
                }
                NSArray *colorsRGB = [UIColor colorForGGB:color];
                UIColor *outPutColor = [UIColor colorWithRed:[colorsRGB[0] floatValue] / 255.0 green:[colorsRGB[1] floatValue] / 255.0 blue:[colorsRGB[2] floatValue] / 255.0 alpha:alpha];
                [outputMtbArr addObject:outPutColor];
            }
            // 发送蓝牙当前颜色
            ZLog(@"%@",outputMtbArr);
        }
        
    }
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.circleSelectView.transform =  CGAffineTransformScale(tansform, scale ,scale);
        
    } completion:^(BOOL finished) {}];
}

- (NSString *)FormatTime: (int)time {
    
    if (time < 10) {
        return  [NSString stringWithFormat:@"0%d",time];
    }else {
        return  [NSString stringWithFormat:@"%d",time];
    }
}


- (void)setupSubView {
    
    Z_WEAK_SELF
    ZZBottomSelectView *bottonView = [ZZBottomSelectView xibInstance];
    self.bottomView = bottonView;
    bottonView.selectBtnClick = ^(NSInteger index) {
        
        self.selectTopBtnModel = index;
        switch (index) {
            case 0:
            {
                [self selectBtnOne];
            }
                break;
            case 1:
            {
                [self selectBtnTwo];
            }
                break;
            case 2:
            {
                [self selectBtnThree];
            }
                break;
                
            default:
                break;
        }
    };
    
    [bottonView TypeTwo];
    bottonView.frame = CGRectMake(40 * Z_Scale , 20 * Z_Scale + 64, Z_SCREEN_WIDTH - 40 * Z_Scale * 2, 33);
    [self.view addSubview:bottonView];
    
    UIButton *addMusicBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.addMusicBtn = addMusicBtn;



    if (self.playMusicList.count > 0) {
        
        addMusicBtn.hidden = YES;
    }


    [addMusicBtn setTitle:NSLocalizedString(@"MUSIC_AddMusic", nil) forState:UIControlStateNormal];
    [self.addMusicBtn addTarget:self action:@selector(addMusicBtnDidClick) forControlEvents:UIControlEventTouchDown];
    self.addMusicBtn.frame = CGRectMake(Z_SCREEN_WIDTH / 2 - 30, CGRectGetMaxY(bottonView.frame) + 29 * Z_Scale, 80, 24);
    self.addMusicBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [self.view addSubview:addMusicBtn];
    self.addMusicBtn.layer.borderWidth = 1;
    self.addMusicBtn.layer.borderColor = [UIColor zColorWithRed:36 green:36 blue:36].CGColor;
    self.addMusicBtn.layer.masksToBounds = YES;
    self.addMusicBtn.layer.cornerRadius = 12;

    
    self.musicLabel = [UILabel new];
    _musicLabel.font = [UIFont systemFontOfSize:15];
    _musicLabel.textColor = VIEW_BG_White_COLOR;
    self.musicLabel.frame = CGRectMake(0, CGRectGetMaxY(bottonView.frame) + 29 * Z_Scale, Z_SCREEN_WIDTH, 16);
    _musicLabel.textAlignment = NSTextAlignmentCenter;
    NSInteger playerCount = 0;
    if (self.playMusicList.count > 0) {

        for (NSInteger index = 0; index<self.playMusicList.count; index++) {

            if ([self.playMusicList[index] isSelect]) {

                playerCount = index;
                break;
            }
        }
        [self playerForIndex:playerCount];

    }
    
    [self.view addSubview:_musicLabel];
    
    UIImageView *iconViewLeft = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_pinl01"]];
    UIImageView *iconViewRight = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_pinli02"]];

    if(self.playMusicList.count > 0 ){

        for (NSInteger index = 0; index < self.playMusicList.count; index++) {

            ZZMusicModel *model = self.playMusicList[index];
            if (model.isSelect) {

                self.currentIndex = index;
                self.musicLabel.text = model.musicName;

            }
        }
    }
    
    
    ZZProgressView *progressView = [ZZProgressView xibInstance];
    progressView.frame = CGRectMake(0, CGRectGetMaxY(_musicLabel.frame) + 29 * Z_Scale, Z_SCREEN_WIDTH, 22);
    progressView.slider.minimumTrackTintColor = [UIColor redColor];
    progressView.slider.maximumTrackTintColor = [UIColor whiteColor];
    [progressView.slider setThumbImage:[UIImage imageNamed:@"img_yy_gd"] forState:UIControlStateNormal];
    self.progressView = progressView;
    progressView.sliderValueChange = ^(CGFloat value) {
        
        _avAudioPlayer.currentTime = value * _avAudioPlayer.duration;
    };
    [self.view addSubview:progressView];
    
    
    [self.view addSubview:iconViewLeft];
    [self.view addSubview:iconViewRight];
    
    ZSelectView *selectView = [ZSelectView xibInstance];
    selectView.frame = CGRectMake(0, 20*Z_Scale + CGRectGetMaxY(progressView.frame), Z_SCREEN_WIDTH, 18);
    self.selectView = selectView;
    selectView.playModel = ^ (ZSelectPlayModel model){
        
        self.playModel = model;
        [self changePlayModel];
    };
    
    
    selectView.pauseMusic = ^ (BOOL isPlay){
        
        if (self.playMusicList.count == 0) {
            
            return ;
        }
        if(isPlay) {
            
            [_avAudioPlayer prepareToPlay];
            [_avAudioPlayer play];
            
            [self cancleLuYin];
            
            ZZMusicModel *model = self.playMusicList[self.currentIndex];
            model.isPlayer = YES;
            
        } else {
            
            [_avAudioPlayer pause];
            [self cancleLuYin];
            ZZMusicModel *model = self.playMusicList[self.currentIndex];
            model.isPlayer = NO;
        }
        
        
    };
    
    selectView.preMusic = ^ { // 播放上一首
        
        weakSelf.currentIndex--;
        
        [self playerForIndex:weakSelf.currentIndex];
    };
    
    selectView.nextMusic = ^ {
        
        weakSelf.currentIndex++;
        [self playerForIndex:weakSelf.currentIndex];
    };
    
    selectView.listMusic = ^ {
        
        ZZMusicListController * vc = [[UIStoryboard storyboardWithName:@"ZZMusicListController" bundle:nil] instantiateInitialViewController];
        
        if (self.playMusicList.count > self.currentIndex) {
            
            vc.playerModel = self.playMusicList[self.currentIndex];
        }

        vc.pasuseMusic = ^(ZZMusicModel *model, ZZMusicList *musicList) {

            self.selectView.isPlayer = NO;
            self.selectView.pauseMusic(NO);
        };
        
        vc.playerMusic = ^(ZZMusicModel *model,ZZMusicList *musicList){
            
            self.musicList = musicList.musicList;
            self.playMusicList = [NSMutableArray arrayWithArray:self.musicList];
            self.currentIndex = [musicList.musicList indexOfObject:model];
            musicList.isSelect = YES;
            [self playerForIndex:self.currentIndex];
        };
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    [self.view addSubview:selectView];
    
    ZZCenterView *circleView = [[ZZCenterView alloc] initWithFrame:CGRectMake((Z_SCREEN_WIDTH - 250 * Z_Scale)/2, 33 * Z_Scale + CGRectGetMaxY(selectView.frame) + 33 * Z_Scale, 250 * Z_Scale, 250 * Z_Scale)];
    self.circleView = circleView;
    
    UIView *circleSelectView = [UIView new];
    self.circleSelectView = circleSelectView;
    self.circleSelectView.frame =  CGRectMake(0, 0,  250 * Z_Scale,  250 * Z_Scale);
    self.circleSelectView.layer.cornerRadius = 250 * Z_Scale / 2.0;
    self.circleSelectView.layer.masksToBounds = YES;
    [circleView addSubview:circleSelectView];
    
    UIImageView *imageView = [UIImageView zImageViewWithImage:@"img_yzz"];
    imageView.frame = CGRectMake(0, 0,  250 * Z_Scale,  250 * Z_Scale);
    [self.circleView addSubview:imageView];
    
    circleView.backgroundColor = [UIColor zColorWithRed:16 green:16 blue:16];
    circleView.layer.cornerRadius = circleView.frame.size.width / 2;
    [self.view addSubview:circleView];
    
    
    self.inCircleView = [UIView new];
    
    self.inCircleView.center = CGPointMake(250 * Z_Scale / 2.0, 250 * Z_Scale / 2.0);;
    self.inCircleView.bounds = CGRectMake(0, 0, 80, 80);
    self.inCircleView.backgroundColor = [UIColor clearColor];
    self.inCircleView.layer.cornerRadius = 40;
    self.inCircleView.layer.masksToBounds = YES;
    [circleView addSubview:self.inCircleView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.addColorBtn = btn;
    
    btn.center = CGPointMake(self.circleView.center.x, self.circleView.center.y);
    btn.bounds = CGRectMake( 0, 0, 60, 60);
    [btn setImage:[UIImage imageNamed:@"btn_add_s"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(addColorBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.circleView.layer.masksToBounds = YES;
    
    
    // 圆环
    CHcir_Slider *cir = [[CHcir_Slider alloc]init];
    cir.startAngle = -90;
    cir.progress = 0.5;
    self.maxValue = 0.5;
    self.minValue = 0.0;
    cir.progress1 = 0.01;
    cir.guideLineColor = Slider_COLOR_Normal_Two;
    cir.lineWidth = 20;
    cir.frame = CGRectMake(0, 43 * Z_Scale + CGRectGetMaxY(selectView.frame), Z_SCREEN_WIDTH, Z_SCREEN_WIDTH);
    cir.center = circleView.center;
    cir.backgroundColor = [UIColor clearColor];
    [self.view addSubview:cir];
    //    cir.cutoutAngle =  M_PI;
    
    cir.delegate = self;
    //    cir.handleInSideRadius = Z_SCREEN_WIDTH ;
    
    [self.bottomView setIndex:0];
    
    
    iconViewLeft.frame = CGRectMake(40, 53 * Z_Scale + CGRectGetMaxY(selectView.frame), 28 ,20 );
    iconViewRight.frame = CGRectMake(Z_SCREEN_WIDTH - 40 - 28, 53 * Z_Scale + CGRectGetMaxY(selectView.frame), 28 ,20 );
    
    [self.view addSubview:btn];
}

- (void)selectBtnOne {
    
    
    
    for (UIView *view in self.circleSelectView.subviews) {
        
        [view removeFromSuperview];
    }
    
    for (UIView *view in self.inCircleView.subviews) {
        
        [view removeFromSuperview];
    }
    
    
    UIView *view = [ZZCircleTool viewForColors:self.danSeArr viewFrame:self.circleView.bounds];
    view.transform = CGAffineTransformMakeRotation(M_PI / self.danSeArr.count);
    [self.circleSelectView addSubview:view];
    
    UIView *inView = [ZZCircleTool viewForColors:self.danSeArr  viewFrame:self.inCircleView.bounds lineWidth:6 inCircleColor:[UIColor colorWithRed:36/255.0 green:26/255.0 blue:26/255.0 alpha:1]];
    
    
    inView.transform = CGAffineTransformMakeRotation(M_PI / self.danSeArr.count);
    [self.inCircleView addSubview:inView];
}

- (void)selectBtnTwo {
    
    for (UIView *view in self.circleSelectView.subviews) {
        
        [view removeFromSuperview];
    }
    
    for (UIView *view in self.inCircleView.subviews) {
        
        [view removeFromSuperview];
    }
    
    
    UIImageView *imgView = [[UIImageView alloc] init];
    self.circleSelectView.backgroundColor = [UIColor clearColor];
    imgView.frame = self.circleSelectView.bounds;
    imgView.image = [UIImage imageNamed:@"1"];
    [imgView imageWithColor:[self.duoSeArr firstObject]];
    [self.circleSelectView addSubview:imgView];
    
    UIView *inView = [ZZCircleTool viewForColors:self.duoSeArr viewFrame:self.inCircleView.bounds lineWidth:6 inCircleColor:[UIColor colorWithRed:36/255.0 green:26/255.0 blue:26/255.0 alpha:1] midColor:[UIColor blackColor] midColorLength:0];
//    inView.transform = CGAffineTransformMakeRotation(M_PI / 2);
    [self.inCircleView addSubview:inView];
}

- (void)selectBtnThree {
    
    for (UIView *view in self.circleSelectView.subviews) {
        
        [view removeFromSuperview];
    }
    
    for (UIView *view in self.inCircleView.subviews) {
        
        [view removeFromSuperview];
    }
    
    UIView *view = [ZZCircleTool viewForColors:self.moreDuoSeArr viewFrame:self.circleView.bounds];
    view.transform = CGAffineTransformMakeRotation(M_PI / 2);
    [self.circleSelectView addSubview:view];
    
    ZZView *inView = [ZZCircleTool viewForColors:self.moreDuoSeArr  viewFrame:self.inCircleView.bounds lineWidth:6 inCircleColor:[UIColor colorWithRed:36/255.0 green:26/255.0 blue:26/255.0 alpha:1]];
    inView.transform = CGAffineTransformMakeRotation(M_PI / 2);
    self.mtbTiaoPinColor = inView.colors;
    [self.inCircleView addSubview:inView];
}

#pragma mark - 播放音乐
- (void)playerForIndex:(NSInteger)index {
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
   
    [self cancleLuYin];
    if (self.playMusicList.count == 0) {
        
        return;
        
    }


    self.addMusicBtn.hidden = YES;
    self.musicLabel.hidden = NO;
    if (index < 0) { // 第一首的上一首是最后一首
        
        index = self.playMusicList.count - 1;
        self.currentIndex = index;
    } else if (index >= self.playMusicList.count) { // 最后一首的下一首是第一首
        
        index = 0;
        self.currentIndex = index;
    }
    
    if (_timer !=nil) {
        
        [_timer invalidate];
        _timer = nil;
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(playProgress) userInfo:nil repeats:YES];
    if (self.playMusicList.count == 0) {
        
        return;
    }
    
    NSURL *path = [self.playMusicList[index] path];
    self.musicLabel.text = [self.playMusicList[index] musicName];

    for (ZZMusicModel *model in self.musicList) {

        model.isSelect = NO;
    }
     self.musicList[index].isSelect = YES;
    self.playMusicList[index].isSelect = YES;

    // (3)初始化音频类 并且添加播放文件
    _avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:nil];
    _avAudioPlayer.meteringEnabled = YES;
    // (4) 设置代理
    _avAudioPlayer.delegate = self;
    
    // (5) 设置初始音量大小 默认1，取值范围 0~1
    _avAudioPlayer.volume = 1;
    NSInteger duration = _avAudioPlayer.duration;
    self.currentDuration = duration;
    
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateFormat = @"mm:ss";
    NSString *durationStr = [formatter stringFromDate: [NSDate dateWithTimeIntervalSinceReferenceDate:self.currentDuration]];
    self.progressView.rightLabel.text = durationStr;
    self.progressView.slider.value = 0;
    self.progressView.leftLabel.text = @"00:00";
    // (6)设置音乐播放次数 负数为一直循环，直到stop，0为一次，1为2次，以此类推
    _avAudioPlayer.numberOfLoops = 0;
    self.selectView.isPlayer = YES;
    
    [_avAudioPlayer play];
    
    [self cancleLuYin];

    [[MusicTool new] save];

}

#pragma mark - play Music
- (void)changePlayModel {
    
    
    if (self.playMusicList.count == 0) {
        
        return;
    }
    
    if ((self.playModel % 3) == 0) {
        
        self.playModel = 0;
    }
    
    switch (self.playModel) {
        case 1:
        {
            self.playMusicList = [NSMutableArray arrayWithArray:@[self.playMusicList[self.currentIndex]]];
        }
            break;
        case 0:
        {
            
            self.playMusicList = [NSMutableArray arrayWithArray:self.musicList];
        }
            break;
        case 2:
        {
            // 随机播放
            
            NSInteger count = self.musicList.count;
            ZZMusicModel *model = self.playMusicList[self.currentIndex];
            NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:self.musicList];
            [self.playMusicList removeAllObjects];
            for (NSInteger index = 0; index < count; index++) {
                
                int random = arc4random() % mutableArr.count;
                [self.playMusicList addObject:mutableArr[random]];
                [mutableArr removeObjectAtIndex:random];
            }
            
            self.currentIndex = [self.playMusicList indexOfObject:model];
            
            
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - AVAudioPlayerDelegate
// 当播放完成时执行的代理
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    
    ZLog(@"audioPlayerDidFinishPlaying");
    _timer = nil;
    [_timer invalidate];
    
    // 播放下一首
    self.currentIndex++;
    [self playerForIndex:self.currentIndex];
    
}
// 当播放发生错误时调用
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error {
    ZLog(@"播放发生错误%@",error);
}
// 当播放器发生中断时调用 如来电
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    
    ZLog(@"audioPlayerBeginInterruption");
    // 暂停播放 用户不暂停，系统也会帮你暂停。但是如果你暂停了，等来电结束，需要再开启
    [_avAudioPlayer pause];
    
    [self cancleLuYin];
    
    
    
    self.playMusicList[self.currentIndex].isPlayer = NO;
}
// 当中断停止时调用 如来电结束
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags {
    
    //3.缓冲
    [_avAudioPlayer prepareToPlay];
    ZLog(@"audioPlayerEndInterruption");
    // 你可以帮用户开启 也可以什么都不执行，让用户自己决定
    [_avAudioPlayer play];
    self.playMusicList[self.currentIndex].isPlayer = NO;
    
    [self cancleLuYin];
    
}


#pragma mark - CHcirsliderDelegate
- (void)minIntValueChanged:(CGFloat)minIntValue{
    
    if (self.minValue <= self.maxValue) {
        
        self.minValue = minIntValue;
    }
    
}

- (void)maxIntValueChanged:(CGFloat)maxIntValue{
    
    if (self.maxValue >= self.minValue) {
        
        self.maxValue = maxIntValue;
    }
}

#pragma mark - set & get
- (NSMutableArray<ZZMusicModel *> *)musicList {
    
    if (!_musicList) {
        
        MusicTool *tool = [MusicTool new]   ;
        for (ZZMusicList *list in tool.listModels.listgroup) {

            if (list.isSelect) {

                _musicList = list.musicList;
            }
        }

        if (_musicList == nil) {

            _musicList = [NSMutableArray array];
        }
    }
    
    return _musicList;
}

- (NSMutableArray *)danSeArr {
    
    if (!_danSeArr) {
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray *oneArr = [defaults objectForKey:kOneColor];
        NSArray *twoArr = [defaults objectForKey:kTwoColor];
        
        if (oneArr== nil || twoArr == nil) {
            
               _danSeArr = [NSMutableArray arrayWithArray:@[[UIColor zColorWithRed:255.0 green:0 blue:0],[UIColor zColorWithRed:0 green:0 blue:255.0]]];
        } else {
            
            UIColor *color1 = [UIColor zColorWithRed:[oneArr[0] floatValue] green:[oneArr[1] floatValue] blue:[oneArr[2] floatValue]];
             UIColor *color2 = [UIColor zColorWithRed:[twoArr[0] floatValue] green:[twoArr[1] floatValue] blue:[twoArr[2] floatValue]];
            
            _danSeArr = [NSMutableArray arrayWithArray:@[color1,color2]];
        }
    }
    return _danSeArr;
}

-(NSMutableArray *)duoSeArr {
    if (!_duoSeArr) {
        
        _duoSeArr = [NSMutableArray arrayWithArray:[ZZColorRGBA colorsFromRGBA:self.duoseModel.colors]];
    }
    return _duoSeArr;
}

-(ZZLightViewCellModel *)moreDuoSeModel {
    
    if (!_moreDuoSeModel) {
        
        NSMutableArray *models  = [[[ZZMusicMoreLightTool new] lightGroup] models];
        
        for (ZZLightViewCellModel *model in models) {
            
            if (model.isSelect) {
                
                _moreDuoSeModel = model;
                
                break;
            }
        }
    }
    return _moreDuoSeModel;
}

- (NSMutableArray *)moreDuoSeArr {
    
    if (!_moreDuoSeArr) {
        
       _moreDuoSeArr = [NSMutableArray arrayWithArray:[ZZColorRGBA colorsFromRGBA:self.moreDuoSeModel.colors]];
    }
    return _moreDuoSeArr;
}

- (ZZLightViewCellModel *)duoseModel {
    
    if (!_duoseModel) {
        
        NSMutableArray *models  = [[[ZZMusicLightTool new] lightGroup] models];
        
        for (ZZLightViewCellModel *model in models) {
            
            if (model.isSelect) {
                
                _duoseModel = model;
                
                break;
            }
        }
    }
    return _duoseModel;
}

- (UIView *)danSeSelectView {
    
    if (!_danSeSelectView) {
        
        _danSeSelectView = [[UIView alloc] init];
        _danSeSelectView.frame = Z_SCREEN;
        _danSeSelectView.backgroundColor = [UIColor clearColor];
        // 蒙版View
        UIView *bgView = [[UIView alloc] init];
        bgView.frame = Z_SCREEN;
        bgView.backgroundColor = [UIColor colorWithDisplayP3Red:36 / 255.0 green:36 / 255.0 blue:36 / 255.0 alpha:0.7];
        [_danSeSelectView addSubview:bgView];
        
        bgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeBackFromSuperView)];
        [bgView setGestureRecognizers:@[tap]];
        
        ZDrawboadView *boadView = [ZDrawboadView xibInstance];
        boadView.isOutPut = YES;
        boadView.center = CGPointMake(Z_SCREEN_WIDTH  / 2, Z_SCREEN_HEIGHT / 2);
        boadView.bounds = CGRectMake(0, 0, 287 * Z_Scale, 287 * Z_Scale);
        boadView.backgroundColor = [UIColor clearColor];
        boadView.viewDidClick = ^(UIColor *color ,AorB style){
            
            
            switch (style) {
                case A:
                {
#pragma mark - 输出A
                    //                NSData *dataA = [color changeData];
                    ZLog(@"%@",color);
                    //                [bleManage writeByte:data index:0 time:0];
                    
                    
                    self.danSeArr = [NSMutableArray arrayWithArray:@[color,self.danSeArr[1]]];
                    [self selectBtnOne];
                    
                }
                    break;
#pragma mark - 输出B
                case B:
                {
                    //                NSData *dataB = [color changeData];
                    ZLog(@"%@",color);
                    self.danSeArr = [NSMutableArray arrayWithArray:@[self.danSeArr[0],color]];
                    [self selectBtnOne];
                }
                    break;
                default:
                    break;
            }
            
            [self saveDanSeColor];
        };
        [_danSeSelectView addSubview:boadView];
    }
    return _danSeSelectView;
}

#pragma mark - removeView
- (void)removeBackFromSuperView {
    
    [self.danSeSelectView removeFromSuperview];
}

- (void)play {
    
    [self playerForIndex:self.currentIndex];
}

- (void)stop {
    
    [_avAudioPlayer stop];
    _timer = nil;
    [_timer invalidate];
}



- (NSMutableArray<ZZMusicModel *> *)playMusicList {

    if (!_playMusicList) {

        _playMusicList = [NSMutableArray arrayWithArray:self.musicList];
    }
    return _playMusicList;
}

































@end

